const getImg = document.querySelector('#getImg');
const content = document.querySelector('#content');
const btnList = document.querySelector('#btnList');
const list = document.querySelector('#list');

let imgList = [];
let items = [];

getImg.onclick = () => {
  fetch('http://192.168.239.166:8080/list/')
  .then(res => res.json())
  .then(res => {
    let len = Math.ceil(res.count/10);
    for(let i=1;i<=len;i++) {
      let btn = document.createElement('button');
      btn.innerHTML = i;
      btn.id = "btn_"+i;
      btnList.appendChild(btn);
      btn.addEventListener('click',function(e){
        if(e.target.nodeName === 'BUTTON') {
          list.innerHTML = '';
          fetch(`http://192.168.239.166:8080/list/?page=${this.id.split('_')[1]}&limit=10`)
          .then(res=>res.json())
          .then(res => {
            imgList = res.data;

            for(let img of imgList) {
              let divNode = document.createElement('div');
              divNode.className = 'item';
              divNode.id = img.id;
              list.appendChild(divNode);
              let pNode = document.createElement('p');
              pNode.innerHTML = img.image_name.split('.')[0];
              let btnNode = document.createElement('button');
              btnNode.className = 'del';
              btnNode.innerHTML = "删除";
              let imgNode = document.createElement('img');
              imgNode.src = img.image_path;
              imgNode.alt = img.image_name;
              
              divNode.appendChild(pNode);
              divNode.appendChild(imgNode);
              divNode.appendChild(btnNode);
            }

            items = document.querySelectorAll('.item');

            for(let item of items) {
              item.addEventListener('click',function(e) {
                if(e.target.nodeName === 'BUTTON') {
                  var xmlhttp = new XMLHttpRequest();
                  xmlhttp.open("DELETE",'/delete/'+this.id,true);
                  xmlhttp.send();

                  this.parentNode.removeChild(this);
                }
              })
            }
          })
        }
      })
    }
  })
};
